#!/bin/bash

echo "=========================================="
echo "  163邮箱SMTP配置向导"
echo "=========================================="
echo ""

echo "📧 请输入您的163邮箱地址："
read -p "邮箱: " SENDER_EMAIL

if [ -z "$SENDER_EMAIL" ]; then
    echo "❌ 邮箱地址不能为空！"
    exit 1
fi

echo ""
echo "🔑 请输入SMTP授权码（不是登录密码！）："
echo "   在163邮箱设置 → POP3/SMTP/IMAP 中获取"
read -sp "授权码: " SMTP_PASSWORD
echo ""

if [ -z "$SMTP_PASSWORD" ]; then
    echo "❌ 授权码不能为空！"
    exit 1
fi

# 备份原配置
echo ""
echo "📦 备份原配置文件..."
cp /aiops/backend/backend/settings.py /aiops/backend/backend/settings.py.bak
echo "✅ 备份完成: settings.py.bak"

# 更新配置文件
echo ""
echo "⚙️  更新配置文件..."
cd /aiops/backend/backend
python3 << PYTHON_EOF
import re

with open('settings.py', 'r', encoding='utf-8') as f:
    content = f.read()

# 替换EMAIL_HOST_USER
content = re.sub(
    r"EMAIL_HOST_USER = '[^']*'",
    f"EMAIL_HOST_USER = '$SENDER_EMAIL'",
    content
)

# 替换EMAIL_HOST_PASSWORD
content = re.sub(
    r"EMAIL_HOST_PASSWORD = '[^']*'",
    f"EMAIL_HOST_PASSWORD = '$SMTP_PASSWORD'",
    content
)

# 替换DEFAULT_FROM_EMAIL
content = re.sub(
    r"DEFAULT_FROM_EMAIL = '[^']*'",
    f"DEFAULT_FROM_EMAIL = '$SENDER_EMAIL'",
    content
)

with open('settings.py', 'w', encoding='utf-8') as f:
    f.write(content)

print("✅ SMTP配置已更新")
PYTHON_EOF

echo ""
echo "=========================================="
echo "  ✅ 配置完成！"
echo "=========================================="
echo ""
echo "已配置："
echo "  发件邮箱: $SENDER_EMAIL"
echo "  授权码: $(echo $SMTP_PASSWORD | sed 's/./*/g')"
echo ""
echo "接下来："
echo "  1. 运行测试: ./test_email.sh"
echo "  2. 如测试成功，重启后端"
echo ""
